package com.jason.library;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author ChenBaoyang
 * @description: MainTest
 * @date 6/30/21 17:12
 */
public class MainTest {

    final String id  = null;

    final String id2 = "123456";
    
    static final String name2 = null;

    static final String name3 = "hhh";
    
    public static void main(String[] args) throws Exception {
        Class<?> clz = MainTest.class;

        setFinalStatic(clz.getDeclaredField("name2"), "xxxxx");
        System.out.println("MainTest.name2 = "+ MainTest.name2);

        setFinalStatic(clz.getDeclaredField("name3"), "yyyyy");
        System.out.println("MainTest.name3 = "+ MainTest.name3);

        MainTest test = new MainTest();
        modify(test, "id", "id_value");
        System.out.println("test.id = "+test.id);

        modify(test, "id2", "id_value2");
        System.out.println("test.id2 = "+test.id2);
    }

    private static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, newValue);
    }

    public static void modify(Object object, String fieldName, Object newFieldValue) throws Exception {
        Field field = object.getClass().getDeclaredField(fieldName);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        //Field 的 modifiers 是私有的
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        field.set(object, newFieldValue);
    }
    
}
